package com.m7788.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.preference.PreferenceManager;
import android.util.Log;

import com.m7788.dao.UploadProDataDaoImpl;
import com.m7788.po.UploadProData;
import com.tool.utils.DBUtil;
import com.tool.utils.DataUtil;

public class AppUtil {
	private static DBUtil mDBUtil;
	public static String setPhotoFileName() {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"'IMG'_yyyy-MM-dd_HH-mm-ss");
		return dateFormat.format(date) + ".jpg";
	}

	public static boolean isValidTagAndAlias(String s) {
		Pattern p = Pattern.compile("^[\u4E00-\u9FA50-9a-zA-Z_-]{0,}$");
		Matcher m = p.matcher(s);
		return m.matches();
	}

	private static void initDbUtil(Context context){
		if(mDBUtil == null){
			mDBUtil = new DBUtil(context);
		}
	}

	/**
	 * 
	 * 方法名：getUserAgent 功能：组装协议头 参数：
	 * 
	 * @param context
	 * @return 创建人：huanghaishui 创建时间：2013-8-14
	 */
	public static String getUserAgent(Context context) {
		initDbUtil(context);
		String userAgent = "pt=2";
		String ver = DataUtil.getAppVersionCode(context);
		String token = AppUtil.getToken(context);
		SharedPreferences mSharedPreference = PreferenceManager.getDefaultSharedPreferences(context);
		String ua = mSharedPreference.getString(Constant.UA,"");
		userAgent = userAgent + "&ver=" + ver + "&token=" + token + "&osver=" + android.os.Build.VERSION.RELEASE + "&ua=" + ua;
//				+ "&city=" + AppUtil.getRecord(context, Constant.CITY)
//				+ "&address=" + AppUtil.getRecord(context, Constant.ADDRESS)
//				+ "&latitude=" + AppUtil.getRecord(context, Constant.LATITUDE)
//				+ "&longitude="
//				+ AppUtil.getRecord(context, Constant.LONGITUDE) + "&province="
//				+ AppUtil.getRecord(context, Constant.PROVINCE) + "&street="
//				+ AppUtil.getRecord(context, Constant.STREET) + "&district="
//				+ AppUtil.getRecord(context, Constant.DISTRICT);
		Log.e("load_token", token);
		return userAgent;
	}
	
	public static String getUserAgent(Context context, String url) {
		initDbUtil(context);
		String userAgent = "pt=2";
		String ver = DataUtil.getAppVersionCode(context);
		String token = getToken(context);
		SharedPreferences mSharedPreference = PreferenceManager.getDefaultSharedPreferences(context);
		String ua = mSharedPreference.getString(Constant.UA,"");
		userAgent = userAgent + "&ver=" + ver + "&token=" + token + "&osver=" + android.os.Build.VERSION.RELEASE + "&ua=" + ua + "&url="+url;
//				+ "&city=" + AppUtil.getRecord(context, Constant.CITY)
//				+ "&address=" + AppUtil.getRecord(context, Constant.ADDRESS)
//				+ "&latitude=" + AppUtil.getRecord(context, Constant.LATITUDE)
//				+ "&longitude="
//				+ AppUtil.getRecord(context, Constant.LONGITUDE) + "&province="
//				+ AppUtil.getRecord(context, Constant.PROVINCE) + "&street="
//				+ AppUtil.getRecord(context, Constant.STREET) + "&district="
//				+ AppUtil.getRecord(context, Constant.DISTRICT);
		Log.e("load_token", token);
		return userAgent;
	}

	public static String getToken(Context context){
		SharedPreferences mSharedPreference = PreferenceManager.getDefaultSharedPreferences(context);
		return mSharedPreference.getString("token","");
	}

	/**
	 * 
	 * 方法名：saveRecord 功能：保存记录 参数：
	 * 
	 * @param context
	 * @param key
	 * @param value
	 *            创建人：huanghaishui 创建时间：2013-8-14
	 */
	public static void saveRecord(Context context, String key, String value) {
		initDbUtil(context);
		mDBUtil.updateOrAddRecord(key, value);
	}

	public static void deleRecord(Context context, String key) {
		initDbUtil(context);
		mDBUtil.deleteRecord(key);
	}

	/**
	 * 
	 * 方法名：getRecord 功能：获取记录 参数：
	 * 
	 * @param context
	 * @param key
	 * @return 创建人：huanghaishui 创建时间：2013-8-14
	 */
	public static  String getRecord(Context context, String key) {
		initDbUtil(context);
		String result = mDBUtil.getRecord(key);
		return result;
	}

	public static Map<String, String> combineHttpParams(String params) {
		String[] arr = params.split("&");
		Map<String, String> parmas = new HashMap<String, String>();
		for (String temp : arr) {
			String[] v = temp.split("=");
			if(v.length>=2){
				parmas.put(v[0], v[1]);
			}
		}

		return parmas;
	}

	public static String UnicodeToGB2312(String str) {

		String res = null;
		StringBuffer sb = new StringBuffer();
		try {
			while (str.length() > 0) {
				if (str.startsWith("%u")) {
					int x = Integer.parseInt(str.substring(2, 6), 16);
					sb.append((char) x);
					str = str.substring(6);
				} else if (str.startsWith("%")) {
					int x = Integer.parseInt(str.substring(1, 3), 16);
					sb.append((char) x);
					str = str.substring(3);
				} else {
					sb.append(str.charAt(0));
					str = str.substring(1);
				}
			}
			res = sb.toString();
		} catch (Exception e) {
			System.err.println("in UnicodeToGB2312:" + e.toString());
		}
		return res;
	}

	public static synchronized boolean isUploadList(Context context) {
		UploadProDataDaoImpl daoImpl = new UploadProDataDaoImpl(context);
		List<UploadProData> dataList = daoImpl.find();
		if (dataList.size() > 0) {
			return true;
		}
		return false;
	}

	public static Bitmap rotate(Bitmap b, float degrees) {
		if (degrees != 0 && b != null) {
			Matrix m = new Matrix();
			m.setRotate(degrees);
			try {
				Bitmap b2 = Bitmap.createBitmap(b, 0, 0, b.getWidth(),
						b.getHeight(), m, true);
				if (b != b2) {
					b.recycle(); // Bitmap操作完应该显示的释放
					System.gc();
					b = b2;
				}
			} catch (OutOfMemoryError ex) {
				// return b;
				// 出现了内存不足异常，最好return 原始的bitmap对象。.
			}
		}
		return b;
	}

	/**
	 * 读取图片属性：旋转的角度
	 * 
	 * @param path
	 *            图片绝对路径
	 * @return degree旋转的角度
	 */
	public static int readPictureDegree(String path) {
		int degree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(path);
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		// Log.e("degree", degree+"");
		return degree;
	}

	/**
	 * 
	 * 方法名：sendMesToActivity 功能：发送消息 参数：
	 * 
	 * @param mContext
	 * @param flag
	 *            1：开始上传图片 2： 上传图片成功 3：上传图片失败 55：刷新头部左边提示 56：刷新头部右边提示
	 * @param desc
	 *            创建人：huanghaishui 创建时间：2013-12-5
	 */
	public static void sendMesToActivity(Context mContext, int flag, String desc) {// 显示提示信息
		Intent intent = new Intent();
		intent.putExtra("operation", flag);
		intent.putExtra("desc", desc);
		intent.setAction(Constant.ACTION_STOA);
		mContext.sendBroadcast(intent);
	}

	public static void clearMemory(Context context) {
		ActivityManager activityManger = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningAppProcessInfo> list = activityManger
				.getRunningAppProcesses();
		if (list != null)
			for (int i = 0; i < list.size(); i++) {
				ActivityManager.RunningAppProcessInfo apinfo = list.get(i);

				String[] pkgList = apinfo.pkgList;

				if (apinfo.importance > ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
					// Process.killProcess(apinfo.pid);
					for (int j = 0; j < pkgList.length; j++) {
						// activityManger.restartPackage(pkgList[j]);
						// 2.2以上是过时的,请用killBackgroundProcesses代替
						activityManger.killBackgroundProcesses(pkgList[j]);
					}
				}
			}
	}

	/**
	 * 
	 * 方法名：getAvailMemory 功能： 参数：
	 * 
	 * @param context
	 * @return 创建人：huanghaishui 创建时间：2014-1-7
	 */
	public static long getAvailMemory(Context context) {
		// 获取android当前可用内存大小
		ActivityManager am = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		MemoryInfo mi = new MemoryInfo();
		am.getMemoryInfo(mi);
		// mi.availMem; 当前系统的可用内存

		// return Formatter.formatFileSize(context, mi.availMem);// 将获取的内存大小规格化
		return mi.availMem / (1024 * 1024);

	}

	public static int computeFileSize(String filePath) {
		int fileSize = 0;
		File file = new File(filePath);
		if (file.exists() && file.isFile()) {
			FileInputStream fis = null;
			try {
				fis = new FileInputStream(file);

				fileSize = fis.available() / 1024;
				// Log.e("fileSize", fileSize+"");
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (fis != null)
						fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return fileSize;

	}

	public static void destroy(){
		mDBUtil = null;
	}
}
